package com.example.shop_2304.fg

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.example.base.mvvm.BaseFragment
import com.example.shop_2304.R
import com.example.shop_2304.adapter.OneCateAdapter
import com.example.shop_2304.adapter.TwoCateAdapter
import com.example.shop_2304.databinding.FragmentCateBinding


class CateFragment : BaseFragment<FragmentCateBinding,CategoryViewModel>() {
    lateinit var oneCateAdapter: OneCateAdapter
    lateinit var twoCateAdapter: TwoCateAdapter
    override fun initView() {
        oneCateAdapter = OneCateAdapter()
        binding.rvOneCate.adapter = oneCateAdapter
        binding.rvOneCate.layoutManager = LinearLayoutManager(context)

        twoCateAdapter = TwoCateAdapter()
        binding.rvTwoCate.adapter = twoCateAdapter
        val layoutManager = LinearLayoutManager(context)
        binding.rvTwoCate.layoutManager = layoutManager

        //请求数据
        viewModel.category()

        //点击左侧 ，右侧对应item置顶
        oneCateAdapter.setOnItemClickListener { adapter, view, position ->
            oneCateAdapter.setType(oneCateAdapter.data[position].id)
            layoutManager.scrollToPositionWithOffset(position,0)
        }
        //滑动右侧，当显示新的item时，左侧选中的item发生变化（监听滑动变化）
        binding.rvTwoCate.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            //找到显示的下标
            val po = layoutManager.findFirstVisibleItemPosition()
            if(twoCateAdapter.data[po].id!=oneCateAdapter.selectedType){//一致的时候不用发生变化   不一致时，one选中的发生变化
                oneCateAdapter.setType(twoCateAdapter.data[po].id)
            }
        }
    }

    override fun initData() {
        viewModel.categorySuccess.observe(this){
            if(it.code==200){
                //一级显示
                oneCateAdapter.data.clear()
                oneCateAdapter.data.addAll(it.data)
                oneCateAdapter.notifyDataSetChanged()
                //二级显示

                twoCateAdapter.data.clear()
                twoCateAdapter.data.addAll(it.data)
                twoCateAdapter.notifyDataSetChanged()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
    }

    override fun getLayout(): Int = R.layout.fragment_cate

    override fun getViewModel(): Class<CategoryViewModel>  = CategoryViewModel::class.java

}